//依赖
var fs=require('fs');
var moment=require('moment');
var config=require('./config.js');
moment.locale(config.MOMENT_LOCALE);

/**
 * 文件移动
 * @param src
 * @param dest
 */
exports.moveFile=function(src, dest){
    var readStream=fs.createReadStream(src);
    var writeStream=fs.createWriteStream(dest);
    readStream.pipe(writeStream);
    readStream.on('end',function(){
        fs.unlinkSync(src);
    });
};

/**
 * 字节格式化
 * @param size
 * @param dec
 * @returns {string}
 */
exports.byteFormat=function(size, dec){
    var units=["B", "KB", "MB", "GB", "TB", "PB","EB","ZB","YB"];
    var position=0;
    while (size>=1024){
        size/=1024;
        position++;
    }
    return (+size.toFixed(dec||0))+' '+units[position];
};

/**
 * 获取文件系统里的文件信息
 * @param dir
 * @param callback
 */
exports.getFileList=function(dir, callback){
    var that=this;
    fs.readdir(dir, function(err, files){
        var fileList=[];
        files.forEach(function(file){
            var stat=fs.statSync(dir+file);
            var date=new Date(stat.ctime);
            fileList.push({
                name:file,
                size:that.byteFormat(stat.size),
                date:moment(date).format('l')
            });
        });
        callback(fileList);
    });
};

/**
 * 返回JSON数据
 * @param res
 * @param data
 */
exports.responseJson=function(res, data){
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.write(JSON.stringify(data));
    res.end();
};